/* Copyright (c) 2008 LepomisLab.com, Andrey Turkin
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "NSScrollView.h"
#include "NSKeyedUnarchiver.h"

IMPLEMENT_DYNAMIC_CLASS(NSScrollView, NSView)

NSScrollView::NSScrollView() : NSView()
{
	_scroll = NULL;
}

void NSScrollView::initWithUnarchiver(NSKeyedUnarchiver *archiver)
{
	NSView::initWithUnarchiver(archiver);

	archiver->decodeObjectForKey(wxT("NSHScroller"));
	archiver->decodeObjectForKey(wxT("NSVScroller"));
	archiver->decodeObjectForKey(wxT("NSContentView"));

	if (archiver->contains(wxT("NSsFlags")))
		archiver->decodeIntForKey(wxT("NSsFlags"));

	if (archiver->contains(wxT("NSHeaderClipView")))
		archiver->decodeObjectForKey(wxT("NSHeaderClipView"));
	
}


void NSScrollView::_releaseWidget(void)
{
	if (_scroll)
	{
		_scroll->Destroy();
		_scroll = NULL;
	}
}

wxWindow* NSScrollView::_allocWidget(NSView *parent)
{
	wxWindow* pwidget = parent->widget();
	if (pwidget)
	{
		_scroll = new wxScrolledWindow(pwidget, wxID_ANY);
		wxASSERT(_scroll);
		_initWidget(_scroll);
		_scroll->SetSizer(new wxBoxSizer(wxHORIZONTAL));
		tile();
	}
	return _scroll;
}

void NSScrollView::setSize(const wxRect& newSize) // NSScrollView always set client to fully populate its client area
{
	if (_frame == newSize)
		return;

	_frame = newSize;
	if (_scroll)
	{
		_initWidget(_scroll);
		tile();
	}
}

void NSScrollView::tile(void)
{
	if (subviews()->length() > 0)
	{
		NSView *subview = wxDynamicCast(subviews()->getObject(0), NSView);
		wxASSERT(subview);
		wxRect clientSize(_scroll->GetClientSize());
		subview->setSize(clientSize);
	}
}
